<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { getSolutionDetailApi } from '@/api/problem/solution';
import MarkdownViewer from '@/components/MarkdownViewer.vue';
import { Message } from '@arco-design/web-vue';

const route = useRoute();
const router = useRouter();
const solutionDetail = ref<API.Problem.SolutionVo | null>(null);
const isLoading = ref(true);

const fetchSolutionDetail = async (id: string) => {
  isLoading.value = true;
  try {
    const res = await getSolutionDetailApi(id);
    if (res.code === 0 && res.data) {
      solutionDetail.value = res.data;
    } else {
      Message.error(res.message || '获取题解详情失败');
    }
  } catch (error: any) {
    Message.error(error.message || '获取题解详情时发生错误');
  } finally {
    isLoading.value = false;
  }
};

const goToProblemDetail = () => {
  if (solutionDetail.value && solutionDetail.value.problemId) {
    router.push(`/problem/${solutionDetail.value.problemId}`);
  }
};

onMounted(() => {
  const solutionId = route.params.solutionId as string;
  if (solutionId) {
    fetchSolutionDetail(solutionId);
  } else {
    Message.error('未提供题解ID');
    isLoading.value = false;
  }
});
</script>

<template>
  <div class="solution-detail-page">
    <a-spin :loading="isLoading" style="width: 100%; min-height: 300px;">
      <a-card v-if="solutionDetail && !isLoading" :title="solutionDetail.title">
        <a-descriptions :column="1" bordered size="large">
          <a-descriptions-item label="作者">
            {{ solutionDetail.username || '匿名用户' }}
          </a-descriptions-item>
          <a-descriptions-item label="创建时间">
            {{ solutionDetail.createTime ? new Date(solutionDetail.createTime).toLocaleString() : '未知' }}
          </a-descriptions-item>
        </a-descriptions>

        <a-divider orientation="left">题解内容</a-divider>
        <div class="solution-content">
          <MarkdownViewer v-if="solutionDetail.content" :value="solutionDetail.content" />
          <a-empty v-else description="暂无题解内容" />
        </div>

        <div v-if="solutionDetail.problemId" class="actions-footer">
          <a-button type="primary" @click="goToProblemDetail">
            查看原题
          </a-button>
        </div>
      </a-card>
      <a-result v-else-if="!isLoading && !solutionDetail" status="error" title="加载失败">
        <template #subtitle>无法获取题解详情，请检查题解ID是否正确或稍后重试。</template>
      </a-result>
    </a-spin>
  </div>
</template>

<style scoped>
.solution-detail-page {
  max-width: 1000px;
  margin: 20px auto;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
}

.solution-content {
  margin-top: 20px;
  padding: 15px;
  border: 1px solid var(--color-border-2);
  border-radius: 4px;
  background-color: var(--color-fill-1);
}

:deep(.arco-descriptions-item-label-block) {
  font-weight: bold;
}

.actions-footer {
  margin-top: 20px;
  text-align: right;
}
</style> 